package com.songyang.mqttandothers.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.songyang.NotOnlyRedisLock.anno.Semaphore;
import com.songyang.mqttandothers.bean.DeviceBean;
import com.songyang.mqttandothers.common.MqttConfiguration;
import com.songyang.mqttandothers.mapper.DeviceMapper;
import com.songyang.mqttandothers.service.DeviceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, DeviceBean> implements DeviceService {
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private RedisTemplate redisTemplate;


    @Override
    public Integer bind(Integer userId, Integer deviceId, String deviceName) {
        DeviceBean deviceBean = new DeviceBean();
        deviceBean.setDeviceId(deviceId);
        deviceBean.setUserId(userId);
        deviceBean.setDeviceChannel(MqttConfiguration.TOPIC + ":" + deviceId);
        deviceBean.setCreateTime(getTime());
        deviceBean.setDeviceName(deviceName);
        int insert = deviceMapper.insert(deviceBean);
        if (insert > 0) {
            QueryWrapper<DeviceBean> queryWrapper = new QueryWrapper<DeviceBean>().eq("user_id", userId).eq("device_id", deviceId);
            DeviceBean getDeviceBean = deviceMapper.selectOne(queryWrapper);
            return getDeviceBean.getDeviceId();
        } else return -1;
    }

    @Override
    public boolean unBind(Integer userId, Integer deviceId) {
        QueryWrapper<DeviceBean> queryWrapper = new QueryWrapper<DeviceBean>().eq("user_id", userId).eq("device_id", deviceId);
        int delete = deviceMapper.delete(queryWrapper);
        if (delete > 0) return true;
        else return false;
    }

    @Semaphore(SemaphoreCounts = 100, isUseDefault = true)
    @Override
    public String getChannel(Integer userId, Integer deviceId) {
        String topicKey = "topic:" + userId + ":" + deviceId;
        String redisTopic = (String) redisTemplate.opsForValue().get(topicKey);
        if (redisTopic == null) {
            QueryWrapper<DeviceBean> queryWrapper = new QueryWrapper<DeviceBean>().eq("user_id", userId).eq("device_id", deviceId);
            DeviceBean deviceBean = deviceMapper.selectOne(queryWrapper);
            if (deviceBean != null) {
                redisTemplate.opsForValue().set(topicKey, deviceBean.getDeviceChannel());
                redisTemplate.expire(topicKey, 60, TimeUnit.SECONDS);
                log.info("查库找topic:" + deviceBean.getDeviceChannel());
                return deviceBean.getDeviceChannel();
            }else
            return null;
        } else log.info("走redis查的topic：" + redisTopic);
        return redisTopic;
    }

    @Override
    public List<DeviceBean> getAllList(Integer userId) {
        QueryWrapper<DeviceBean> queryWrapper = new QueryWrapper<DeviceBean>().eq("user_id", userId);
        return deviceMapper.selectList(queryWrapper);
    }

    @Override
    public String[] getAllTopic() {
        List<DeviceBean> deviceBeans = deviceMapper.selectList(new QueryWrapper<>());
        String[] result = new String[deviceBeans.size()];
        for (int i = 0; i < deviceBeans.size(); i++) {
            result[i] = deviceBeans.get(i).getDeviceChannel();
//            System.out.println(result[i]);
        }
        return result;
    }


    public String getTime() {
        Date date = new Date();//创建时间
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        return format.format(date);
    }
}
